package com.swm.julie.rest.crud.twitt.insert;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.cjk.CJKAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import com.swm.julie.rest.crud.twitt.TwittDocFormat;

public class InsertTwitt {

	private IndexWriter writer;
	private TwittDocFormat twitt;
	
	protected InsertTwitt(TwittDocFormat twitt) 
	{
		this.twitt = twitt;
	}
	
	private void close() throws CorruptIndexException, IOException
	{
		writer.close();
		this.twitt = null;
	}
	
	/**
	 * Main logic of inserting twitt to indexing folder.
	 * First, check uniqueness of the id then progress the inserting it.
	 * (In Lucene, indexing acts like insert.)
	 * 
	 * @param indexDir
	 * @return completeness of indexing twitt.
	 * @throws IOException
	 */
	protected boolean insertTwiit(String indexDir) throws IOException
	{
		Directory dir = FSDirectory.open(new File(indexDir));
		writer = new IndexWriter(dir, new IndexWriterConfig(Version.LUCENE_33, new CJKAnalyzer(Version.LUCENE_33)));

		if(isValidId(twitt.getId()))
		{
			writer.addDocument(addDocument());
			close();
			return true;
		}else
		{
			close();
			return false;
		}
	}
	
	/**
	 * Add the indexing information.
	 */
	private Document addDocument()
	{
		Document doc = new Document();
		
		doc.add(new Field("id", String.valueOf(this.twitt.getId()), Field.Store.YES, Field.Index.NOT_ANALYZED));
		doc.add(new Field("postdate", String.valueOf(this.twitt.getPostdate()), Field.Store.YES, Field.Index.ANALYZED));
		doc.add(new Field("contents", this.twitt.getContents(), Field.Store.YES, Field.Index.ANALYZED));
		doc.add(new Field("linkInfo", this.twitt.getLinkInfo(), Field.Store.YES, Field.Index.ANALYZED));
		doc.add(new Field("url", this.twitt.getPostUrl(), Field.Store.YES, Field.Index.ANALYZED));
		
		return doc;
	}
	
	/**
	 * check the existence of input ID value in indexed ID because id is the unique value for each twitt. 
	 * @param id
	 * @return
	 */
	public boolean isValidId(long id)
	{
		return true;
	}
}
